package com.weike.bsp.security.authentication.captcha

import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import org.springframework.security.web.server.authentication.AuthenticationWebFilter
import org.springframework.stereotype.Component

/**
 * @author tiger
 * -- create at 2019-05-30 15:58
 *
 * 需要验证码
 *
 * @see UsernamePasswordAuthenticationFilter
 */
@Component
class CaptchaAuthenticationFilter(
    private val authenticationManager: ReactiveAuthenticationManager
) : AuthenticationWebFilter(authenticationManager) {

    private var captchaParameter = SPRING_SECURITY_FORM_CAPTCHA_KEY

//    @Throws(AuthenticationException::class)
//    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
//        val captcha = obtainCaptcha(request)
//        val rawCaptcha = request.session.getAttribute(Constant.CAPTCHA_SESSION_KEY)
//
//        if (!StringUtils.equalsIgnoreCase(captcha, rawCaptcha.toString())) {
//            throw BadCaptchaException("验证码错误")
//        }
//        return super.attemptAuthentication(request, response)
//    }

//    override fun setServerAuthenticationConverter(authenticationConverter: ServerAuthenticationConverter?) {
//        super.setServerAuthenticationConverter(authenticationConverter)
//    }

//    /**
//     * @see .obtainUsername
//     */
//    protected fun obtainCaptcha(request: HttpServletRequest): String? {
//        return request.getParameter(captchaParameter)
//    }

//    /**
//     * Sets the parameter name which will be used to obtain the username from the login
//     * request.
//     *
//     * @param captchaParameter the parameter name. Defaults to "username".
//     */
//    fun setCaptchaParameter(captchaParameter: String) {
//        Assert.hasText(captchaParameter, "Captcha parameter must not be empty or null")
//        this.captchaParameter = captchaParameter
//    }
//
//    fun getCaptchaParameter(): String {
//        return captchaParameter
//    }

//    @Autowired
//    override fun setAuthenticationManager(authenticationManager: AuthenticationManager) {
//        super.setAuthenticationManager(authenticationManager)
//    }
//
//    @Autowired
//    override fun setAuthenticationFailureHandler(failureHandler: AuthenticationFailureHandler) {
//        super.setAuthenticationFailureHandler(failureHandler)
//    }
//
//    @Autowired
//    override fun setAuthenticationSuccessHandler(successHandler: AuthenticationSuccessHandler) {
//        super.setAuthenticationSuccessHandler(successHandler)
//    }

    companion object {
        const val SPRING_SECURITY_FORM_CAPTCHA_KEY = "verifyCode"
    }
}
